package com.epfresh.supplier.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageSize;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.api.widget.PhotoUploadView;
import com.epfresh.api.widget.gradient.utils.LinearGradientUtil;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.Category;
import com.epfresh.supplier.entity.StoreBaseInfo;
import com.epfresh.supplier.view.tag.FlowLayout;
import com.epfresh.supplier.view.tag.TagAdapter;
import java.util.ArrayList;
import java.util.List;

public class ApplyOpenFirstFragment extends BaseFragment implements PhotoCore.PhotoResult {
    private CommonInputItem vStoreName;
    private CommonInputItem vStoreCategory;
    private CommonInputItem vMarket;
    private CommonInputItem vMarketId;
    private CommonInputItem vCity;
    private CommonInputItem vMarketArea;
    private CommonInputItem vDescription;
    //  private TagFlowLayout categoryTag;
    private TagAdapter<Category> adapter;
    private List<Category> listCategory = new ArrayList<>();
    private View rlOrder;
    private View rlRefuse;
    private TextView tvRefuse;
    private TextView tvBtn;
    private TextView tvCacheSave;
    private View vStoreEnsure;
    private TextView tvBackTitle;
    private PhotoUploadView vStoreAvater;
    private int TYPE;
    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "store_avatar";
    private boolean isFirst = true;
    private StoreBaseInfo currentStoreInfo = new StoreBaseInfo();
    private String currentLogoPath = "";
    private int w;
    private int top = -1;
    private LinearGradientUtil linearGradientUtil;
    private String merchantId;


    @Override
    public String getBaseTag() {
        return "ApplyOpenFirstFragment";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.applyopenfirst, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        filePath += "_" + getUser().getAccountId();
        if (savedInstanceState != null) {
            getActivity().getIntent().putExtra(Constant.KEY_STORE_TYPE_STATUS, savedInstanceState.getInt(Constant.KEY_STORE_TYPE_STATUS));
        }
        initPhotoCore();
        initData();
    }

    private void initView(View view) {
        vStoreName = view.findViewById(R.id.ci_store_name);
        vStoreCategory = view.findViewById(R.id.ci_store_category);
        vCity = view.findViewById(R.id.ci_city);
        vMarket = view.findViewById(R.id.ci_market_address);
        vMarketArea = view.findViewById(R.id.ci_market_area);
        vMarketId = view.findViewById(R.id.ci_market_id);
        vDescription = view.findViewById(R.id.ci_description);

        vStoreCategory.setOnClickListener(this);
        vMarketArea.setOnClickListener(this);

        vStoreName.setOnCanNotEdit(onCanNotEdit);
        vStoreCategory.setOnCanNotEdit(onCanNotEdit);
        vCity.setOnCanNotEdit(onCanNotEdit);
        vMarket.setOnCanNotEdit(onCanNotEdit);
        vMarketArea.setOnCanNotEdit(onCanNotEdit);
        vMarketId.setOnCanNotEdit(onCanNotEdit);
        w = LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(50);
        w /= 4;
        //categoryTag = (TagFlowLayout) findViewById(R.id.tag_category);

        adapter = new TagAdapter<Category>(listCategory) {
            @Override
            public View getView(FlowLayout parent, int position, Category category) {
                TextView tv = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.category_market_tag,
                        parent, false);


                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();
                lp.width = w;
//                lp.leftMargin = LocalDisplay.dp2px(8);
//                lp.topMargin = LocalDisplay.dp2px(10);
//
//
//                lp.height = LocalDisplay.dp2px(30);
                tv.setLayoutParams(lp);
                tv.setText(category.getName());
                return tv;
            }
        };

//        categoryTag.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
//            @Override
//            public boolean onTagClick(View view, int position, FlowLayout parent) {
//
//                if (position < listCategory.size()) {
//                    Category c = listCategory.get(position);
//                    if ("-1".equals(c.getId())) {
//                        String id = currentStoreInfo.getMainBusinessCategoryIds();
//                        if ("-1".equals(id)) {
//                            adapter.setSelectedList(new HashSet<Integer>());
//                            vStoreCategory.setContentText("");
//                            currentStoreInfo.setMainBusinessCategoryIds(null);
//                            currentStoreInfo.setMainBusinessCategoryNames(null);
//                        } else {
//                            adapter.setSelectedList(position);
//                            vStoreCategory.setContentText(c.getName());
//                            currentStoreInfo.setMainBusinessCategoryIds(c.getId());
//                            currentStoreInfo.setMainBusinessCategoryNames(c.getName());
//                        }
//                    } else {
//                        Set<Integer> selectPosSet = categoryTag.getSelectedList();
//                        StringBuilder sb = new StringBuilder();
//                        StringBuilder sb2 = new StringBuilder();
//                        ArrayList<Integer> list = new ArrayList<Integer>();
//                        Set<Integer> set = new HashSet<Integer>();
//                        if (selectPosSet != null && selectPosSet.size() > 0) {
//                            for (Integer i : selectPosSet) {
//
//                                Category category = listCategory.get(i);
//                                if (!"-1".equals(category.getId())) {
//                                    list.add(i);
//                                    set.add(i);
//                                }
//                            }
//
//                            if (list.size() > 0) {
//                                Collections.sort(list, new Comparator<Integer>() {
//                                    @Override
//                                    public int compare(Integer o1, Integer o2) {
//                                        return o1 - o2;
//                                    }
//                                });
//                                for (int i = 0; i < list.size(); i++) {
//
//                                    Category category = listCategory.get(list.get(i));
//                                    sb.append(category.getName());
//                                    sb.append(",");
//                                    sb2.append(category.getId());
//                                    sb2.append(",");
//                                }
//                            }
//
//                            if (sb.toString().length() > 0 && sb.toString().lastIndexOf(",") == sb.toString().length() - 1) {
//                                sb.delete(sb.toString().length() - 1, sb.toString().length());
//                            }
//                            if (sb2.toString().length() > 0 && sb2.toString().lastIndexOf(",") == sb2.toString().length() - 1) {
//                                sb2.delete(sb2.toString().length() - 1, sb2.toString().length());
//                            }
//
//
//                            adapter.setSelectedList(set);
//                            vStoreCategory.setContentText(sb.toString());
//                            currentStoreInfo.setMainBusinessCategoryIds(sb2.toString());
//                            currentStoreInfo.setMainBusinessCategoryNames(sb.toString());
//                        } else {
//                            vStoreCategory.setContentText("");
//                            currentStoreInfo.setMainBusinessCategoryIds(null);
//                            currentStoreInfo.setMainBusinessCategoryNames(null);
//                        }
//                    }
//                }
//
//                return true;
//            }
//        });
//
//
//        categoryTag.setAdapter(adapter);


        rlRefuse = view.findViewById(R.id.rl_refuse_reason);
        tvRefuse =  view.findViewById(R.id.tv_refuse_content);
        vStoreAvater =  view.findViewById(R.id.rl_store_avater);
        tvBtn =  view.findViewById(R.id.tv_btn);
        tvCacheSave =  view.findViewById(R.id.tv_save_cache);
        tvCacheSave.setOnClickListener(this);
        vStoreEnsure =  view.findViewById(R.id.iv_store_ensuring);

        vStoreAvater.setOnClickListener(this);
        tvBtn.setOnClickListener(this);

        vMarket.setOnClickListener(this);
        vCity.setOnClickListener(this);

        TYPE = getActivity().getIntent().getIntExtra(Constant.KEY_STORE_TYPE_STATUS, -1);
        //第一次开店
//        if (TYPE == Constant.TYPE_STORE_STATUS_FIRST_OPEN) {
//            isFirst = true;
//            first();
////            cmdStoreInfo = "store/info";
//            requestUnPostStoreInfo();
//        } else if (TYPE == Constant.TYPE_STORE_STATUS_EDIT) {//再次编辑
//            isFirst = false;
//            edit();
////            requestStoreInfo();
//            requestUnPostStoreInfo();
//        } else if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW) {//预览
//            isFirst = false;
//            preview();
//            requestUnPostStoreInfo();
//        } else if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW_EDIT) {//预览,可编辑
//            isFirst = false;
//            previewEdit(true);
//            requestUnPostStoreInfo();
//        } else {//错误
//
//            finish();
//        }

    }

    private void initData() {

    }

    private void initPhotoCore() {
        photoCore = new PhotoCore(this, getAppActivity());
        photoCore.setResultHeight(240);
        photoCore.setResultWidth(720);
        photoCore.setRatio(720,240);
    }

    View.OnClickListener onCanNotEdit = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (TYPE == Constant.TYPE_STORE_STATUS_PRVIEW) {
                T.toast("店铺审核中不可修改");
            } else {
                T.toast("您仅可修改门头照与店铺简介，如需修改其他，请联系客服：400-0588-198");
            }
        }
    };

    @Override
    public void onSuccess(String path) {
        vStoreAvater.showImage();
        tag.type = RequestTag.TYPE_CURRENT;
        currentLogoPath = path;
        ImageSize imageSize = new ImageSize(200, 200);
        Log.e("sfsaf",""+path);
        ImageLoader.getInstance().displayImage(path, new ImageViewAware(vStoreAvater.getImagView()), vStoreAvater.getImageOption(), imageSize, null, null);
        vStoreAvater.uploadImage(getAppActivity(), filePath, tag);
    }

    @Override
    public void onFail(String msg) {
        T.toast("获取图片失败");
    }

    @Override
    public void onReupload() {
        tag.type = RequestTag.TYPE_CURRENT;
        vStoreAvater.uploadImage(getAppActivity(), filePath, tag);
    }

    RequestTag tag = new RequestTag();
    int picId = Integer.MIN_VALUE;
}
